//% color="#1E90FF" iconWidth=50 iconHeight=40
namespace kimi_vision{

    //% block="初始化kimi API密钥:[API] 模型:[MODEL]" blockType="command"
    //% API.shadow="string" API.defl="YOUR_API"
    //% MODEL.shadow="dropdown" MODEL.options="MODEL"
  
    export function initializeMoonshotAI(parameter: any, block: any) {
        let kimi_api = parameter.API.code;
        let model = parameter.MODEL.code;
       
        Generator.addImport(`import openai`);
        Generator.addImport(`import base64`);
        Generator.addImport(`import os`);

        Generator.addCode(`
client = openai.OpenAI(api_key=${kimi_api}, base_url="https://api.moonshot.cn/v1")
kimi_model = "${model}"
kimi_history = [
    {"role": "system", "content": """你是 Kimi，由 Moonshot AI 提供的人工智能助手，能够理解图片内容，包括图片文字、图片颜色和物体形状等内容。"""}
]

def kimi_chat(image_path, kimi_history, kimi_model):
    with open(image_path, "rb") as f:
         image_data = f.read()
    image_url = f"data:image/{os.path.splitext(image_path)[1]};base64,{base64.b64encode(image_data).decode('utf-8')}"
    kimi_history.append({
        "role": "user", 
        "content": [
                {
                    "type": "image_url", # <-- 使用 image_url 类型来上传图片，内容为使用 base64 编码过的图片内容
                    "image_url": {
                        "url": image_url,
                    },
                },
                {
                    "type": "text",
                    "text": "请描述图片的内容。", # <-- 使用 text 类型来提供文字指令，例如“描述图片内容”
                },
            ],
    })
    completion = client.chat.completions.create(
        model=kimi_model,
        messages=kimi_history,
       )
    result = completion.choices[0].message.content
    kimi_history.append({
        "role": "assistant",
        "content": result
    })
    return result
`);
    }

    //% block="发送Base64图像 [image_path] 并返回响应" blockType="reporter"
    //% image_path.shadow="string" image_path.defl="Mind+.png"
    export function sendMessage(parameter: any, block: any) {
        let image_path = parameter.image_path.code;

        Generator.addCode(`kimi_chat(${image_path},kimi_history, kimi_model)`);
    }
 
}
